package skin;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
@RestController
public class SkinAnalysisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SkinAnalysisApplication.class, args);
    }

    @PostMapping("/analyze")
    public List<String> analyzeImages(@RequestParam("image1") MultipartFile image1,
                                     @RequestParam("image2") MultipartFile image2,
                                     @RequestParam("image3") MultipartFile image3) {
        List<String> results = new ArrayList<>();
        
        try {
            // 处理三张图片
            if (!image1.isEmpty()) {
                results.add(processImage(image1));
            }
            if (!image2.isEmpty()) {
                results.add(processImage(image2));
            }
            if (!image3.isEmpty()) {
                results.add(processImage(image3));
            }
        } catch (IOException e) {
            results.add("处理图片时出错: " + e.getMessage());
        }
        
        return results;
    }

    private String processImage(MultipartFile image) throws IOException {
        // 创建临时文件
        String tempDir = System.getProperty("java.io.tmpdir");
        Path tempFilePath = Paths.get(tempDir, image.getOriginalFilename());
        Files.write(tempFilePath, image.getBytes());
        
        File imageFile = tempFilePath.toFile();
        
        try {
            // 调用皮肤分析逻辑
            String result = SkinAnalysisOptimizedcopy.analyzeSkin(imageFile);
            String parsedResult = SkinAnalysisOptimizedcopy.printOptimizedResult(result);
            
            // 删除临时文件
            Files.deleteIfExists(tempFilePath);
            
            return parsedResult;
        } catch (Exception e) {
            // 确保临时文件被删除
            Files.deleteIfExists(tempFilePath);
            throw e;
        }
    }
}